from django.shortcuts import render, redirect
import pymysql
from appBack.utils import DB


# Create your views here.
def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    usr = request.POST.get("name")
    pwd = request.POST.get("password")
    code = request.POST.get("code")
    if code != "6982":
        return redirect("/login/")
    try:
        host = '119.91.139.114'
        user = 'ShiXi'
        password = 'Wey4pPMkyJ2d'
        database = 'django_test'
        connection = pymysql.connect(host=host, user=user, password=password, database=database)
        cursor = connection.cursor()
        query = f"select password from tab where username='{usr}'"
        cursor.execute(query)
        result = cursor.fetchone()
    except Exception as e:
        print(e)
    finally:
        if cursor:
            cursor.close()

    print(result)
    if result and result[0] == pwd:
        return redirect("/index/")
    return render(request, "login.html")

def index(request):
    print(request.path)
    return render(request, 'index.html')


def lol_list(request):
    if request.GET.get('page'):
        offset = (int(request.GET.get('page')) - 1) * 20
    else:
        offset = 0
    mysql = DB(host='119.91.139.114', user='ShiXi', passwd='Wey4pPMkyJ2d', db='django_test')
    live_up = mysql.findall(f'SELECT * FROM django_test.LOL t LIMIT 20 OFFSET {offset}')

    return render(request, 'lol_list.html', {'live_list': live_up})